<template>
  <el-dialog
    title="分配角色"
    :model-value="modelValue"
    @close="closed"
  >
    <el-checkbox-group v-model="userRoleTitleList" @change="handleCheckBoxChange">
      <el-checkbox
        v-for="item in allRoleList"
        :key="item.id"
        :label="item.name"
      ></el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closed">取消</el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getRoleList, getRolesByUserId, updateRoleUsers } from '@/api/role'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  userId: {
    type: String,
    required: true
  }
})

const currentSelect = ref([])

const emits = defineEmits(['update:modelValue', 'updateRole'])

// 所有角色
const allRoleList = ref([])
// 获取所有角色数据的方法
const getLeftData = async () => {
  const result = await getRoleList()
  console.log(JSON.stringify(result))
  allRoleList.value = result
}
getLeftData()

// 当前用户角色
const userRoleTitleList = ref([])
// 获取当前用户角色
const getUserRoles = async () => {
  const res = await getRolesByUserId({
    userId: props.userId
  })
  userRoleTitleList.value = res.map(item => item.name)
}

const handleCheckBoxChange = (value) => {
  currentSelect.value = value
}

watch(
  () => props.userId,
  val => {
    if (val) getUserRoles()
  }
)

/**
  确定按钮点击事件
 */
const onConfirm = async () => {
  // 处理数据结构
  const roles = userRoleTitleList.value.map(title => {
    return allRoleList.value.find(role => role.name === title)
  })

  const ids = roles.map(item => item.id)
  await updateRoleUsers({
    userId: props.userId,
    roleIds: ids.join(',')
  })

  ElMessage.success('用户角色更新成功')
  closed()
  // 角色更新成功
  emits('updateRole')
}

/**
 * 关闭
 */
const closed = () => {
  emits('update:modelValue', false)
}
</script>

<style lang="scss" scoped></style>
